import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test12306 {
    private WebDriver driver;
    @BeforeEach
    public void setup() {
        //提交最终代码脚本时，请将驱动路径换回官方路径"C:\\Users\\86153\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe"
//        System.setProperty("webdriver.chrome.driver", "C:\\Users\\86153\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\hxdeng2\\Desktop\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--remote-allow-origins=*");
        driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.12306.cn/index/index.html");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(java.time.Duration.ofSeconds(10));
    }

//test-code-start

    // 公共方法：导航到车票查询页面
    public void test_meth_public() {
        Actions actions = new Actions(driver);
        // 鼠标悬停在【车票】菜单上

        WebElement ticketMenu2 = driver.findElement(By.xpath("//*[@id=\"J-chepiao\"]/a"));

        // 鼠标悬停在【车票】菜单上
        WebElement ticketMenu = driver.findElement(By.xpath("//*[@id=\"J-chepiao\"]/a"));
        actions.moveToElement(ticketMenu).perform();

        // 点击【单程】链接
        WebElement singleTripLink = driver.findElement(By.xpath("//*[@id=\"megamenu-3\"]/div[1]/ul/li[1]/a"));
        singleTripLink.click();
    }


    // R001: 单程车票查询
    @ParameterizedTest
    @CsvSource({
            "北京北,广州北,2025-09-15,12306_R001_001.png",
            "北京北,广州北,2025-09-22,12306_R001_002.png",
            "北京北,广州北,2025-09-29,12306_R001_003.png"
    })
    public void test_12306_R001(String from, String to, String date, String screen) throws InterruptedException {
        test_meth_public();
        // 输入出发地
        WebElement fromInput = driver.findElement(By.xpath("//*[@id=\"fromStationText\"]"));
        fromInput.click();
        fromInput.sendKeys(Keys.BACK_SPACE);
        fromInput.sendKeys(from);
        fromInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入目的地
        WebElement toInput = driver.findElement(By.xpath("//*[@id=\"toStationText\"]"));
        toInput.click();
        toInput.sendKeys(Keys.BACK_SPACE);
        toInput.sendKeys(to);
        toInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入出发日期
        WebElement startDateInput = driver.findElement(By.xpath("//*[@id=\"train_date\"]"));
        startDateInput.click();
        startDateInput.clear();
        startDateInput.sendKeys(date);
        Thread.sleep(1000);
        // 点击查询按钮
        driver.findElement(By.xpath("//*[@id=\"query_ticket\"]")).click();
        // 等待查询结果加载
        try {
            // 使用显示等待方法等待元素出现
            WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"float\"]")));
            System.out.println("元素已找到");
        } catch (TimeoutException e) {
            System.out.println("等待超时，未找到元素");
        }
        takeScreenshot(screen);
    }

    // R002: 单程车票查询无效日期
    @ParameterizedTest
    @CsvSource({
            "北京北,广州北,2025-09-32,12306_R002_001.png",
            "上海南,深圳北,2025-02-30,12306_R002_002.png"
    })
    public void test_12306_R002(String from, String to, String date, String screen) throws InterruptedException {
        test_meth_public();
        // 输入出发地
        WebElement fromInput = driver.findElement(By.xpath("//*[@id=\"fromStationText\"]"));
        fromInput.click();
        fromInput.sendKeys(Keys.BACK_SPACE);
        fromInput.sendKeys(from);
        fromInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入目的地
        WebElement toInput = driver.findElement(By.xpath("//*[@id=\"toStationText\"]"));
        toInput.click();
        toInput.sendKeys(Keys.BACK_SPACE);
        toInput.sendKeys(to);
        toInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入无效日期
        WebElement startDateInput = driver.findElement(By.xpath("//*[@id=\"train_date\"]"));
        startDateInput.click();
        startDateInput.clear();
        startDateInput.sendKeys(date);
        Thread.sleep(1000);
        Thread.sleep(1000);
        // 点击查询按钮
        driver.findElement(By.xpath("//*[@id=\"query_ticket\"]")).click();
        // 验证错误提示
        try {
            // 使用显示等待方法等待元素出现
            WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10));
            wait.until(ExpectedConditions.textToBePresentInElementLocated(
                    By.xpath("//*[@id=\"no_filter_ticket_6\"]/p"), "查询超时，请稍后再试！"));
            System.out.println("元素已找到");
        } catch (TimeoutException e) {
            System.out.println("等待超时，未找到元素");
        }
        takeScreenshot(screen);
    }

    // R003: 往返车票查询
    @ParameterizedTest
    @CsvSource({
            "天津北,沈阳,2025-09-15,2025-09-15,12306_R003_001.png",
            "天津北,沈阳,2025-09-15,2025-09-22,12306_R003_002.png",
            "天津北,沈阳,2025-09-15,2025-09-29,12306_R003_003.png"
    })
    public void test_12306_R003(String from, String to, String departDate, String returnDate, String screen) throws InterruptedException {
        test_meth_public();
        // 导航到往返车票页面
        WebElement roundTripLink = driver.findElement(By.xpath("//*[@id=\"dfc\"]/ul/li[2]"));
        roundTripLink.click();
        // 输入出发地
        WebElement fromInput = driver.findElement(By.xpath("//*[@id=\"fromStationText\"]"));
        fromInput.click();
        fromInput.sendKeys(Keys.BACK_SPACE);
        fromInput.sendKeys(from);
        fromInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入目的地
        WebElement toInput = driver.findElement(By.xpath("//*[@id=\"toStationText\"]"));
        toInput.click();
        toInput.sendKeys(Keys.BACK_SPACE);
        toInput.sendKeys(to);
        toInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入出发日期
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).sendKeys(departDate);
        Thread.sleep(1000);
        // 输入返程日期
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).sendKeys(returnDate);
        Thread.sleep(1000);
        // 点击查询按钮
        driver.findElement(By.xpath("//*[@id=\"query_ticket\"]")).click();
        // 等待查询结果加载
        try {
            // 使用显示等待方法等待元素出现
            WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"float\"]")));
            System.out.println("元素已找到");
        } catch (TimeoutException e) {
            System.out.println("等待超时，未找到元素");
        }
        takeScreenshot(screen);
    }

    // R004: 往返车票查询无效返程日期
    @ParameterizedTest
    @CsvSource({
            "郑州东,上海,2025-09-15,2025-09-14,12306_R004_001.png",
            "郑州东,上海,2025-09-15,XXXX-XX-XX,12306_R004_002.png"
    })
    public void test_12306_R004(String from, String to, String departDate, String returnDate, String screen) throws InterruptedException {
        test_meth_public();
        // 导航到往返车票页面
        WebElement roundTripLink = driver.findElement(By.xpath("//*[@id=\"dfc\"]/ul/li[2]"));
        roundTripLink.click();

        // 输入出发地
        WebElement fromInput = driver.findElement(By.xpath("//*[@id=\"fromStationText\"]"));
        fromInput.click();
        fromInput.sendKeys(Keys.BACK_SPACE);
        fromInput.sendKeys(from);
        fromInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入目的地
        WebElement toInput = driver.findElement(By.xpath("//*[@id=\"toStationText\"]"));
        toInput.click();
        toInput.sendKeys(Keys.BACK_SPACE);
        toInput.sendKeys(to);
        toInput.sendKeys(Keys.ENTER);
        Thread.sleep(1000);
        // 输入出发日期
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).sendKeys(departDate);
        Thread.sleep(1000);
        // 输入无效返程日期
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).sendKeys(returnDate);
        Thread.sleep(1000);
        // 点击查询按钮
        driver.findElement(By.xpath("//*[@id=\"query_ticket\"]")).click();

        // 验证错误提示
        WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10));
        if (returnDate.equals("2025-09-14")) {
            try {
                // 等待并切换到弹窗
                Alert alert = wait.until(ExpectedConditions.alertIsPresent());
                driver.switchTo().alert();

                // 验证弹窗文本
                wait.until(ExpectedConditions.textToBePresentInElementLocated(
                        By.xpath("//*[@id=\"content_defaultwarningAlert_hearder\"]"), "返回日期不得早于出发日期"));

                // 关闭弹窗
                alert.accept();
            } catch (TimeoutException e) {
                System.out.println("未找到预期的弹窗提示，可能显示了其他错误信息");
            }
        } else {
            try {
                // 验证页面错误提示
                wait.until(ExpectedConditions.textToBePresentInElementLocated(
                        By.xpath("//*[@id=\"no_filter_ticket_6\"]/p"), "查询超时，请稍后再试！"));
            } catch (TimeoutException e) {
                System.out.println("未找到预期的页面错误提示，可能显示了其他错误信息");
            }
        }
        takeScreenshot(screen);
    }

    // R005: 学生票查询s
    @ParameterizedTest
    @CsvSource({
            "福州南,厦门,2025-09-17,2025-09-22,12306_R005_001.png"
    })
    public void test_12306_R005(String from, String to, String departDate, String returnDate, String screen) throws InterruptedException {
        test_meth_public();
        // 导航到往返车票页面
        WebElement roundTripLink = driver.findElement(By.xpath("//*[@id=\"dfc\"]/ul/li[2]"));
        roundTripLink.click();

        // 选择出发地
        WebElement fromInput = driver.findElement(By.xpath("//*[@id=\"fromStationText\"]"));
        fromInput.click();
        driver.findElement(By.xpath("//*[@id=\"nav_list3\"]")).click();
        driver.findElement(By.xpath("//*[@id=\"ul_list3\"]/ul[1]/li[4]")).click();
        Thread.sleep(1000);
        // 输入目的地
        WebElement toInput = driver.findElement(By.xpath("//*[@id=\"toStationText\"]"));
        toInput.click();
        driver.findElement(By.xpath("//*[@id=\"ul_list1\"]/li[33]")).click();
        Thread.sleep(1000);
        // 输入出发日期
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"train_date\"]")).sendKeys(departDate);
        Thread.sleep(1000);
        // 输入返程日期
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).clear();
        driver.findElement(By.xpath("//*[@id=\"back_train_date\"]")).sendKeys(returnDate);
        Thread.sleep(1000);
        // 选择学生票
        driver.findElement(By.xpath("//*[@id=\"queryLeftForm\"]/div[3]/ul/li[2]")).click();
        Thread.sleep(1000);
        // 点击查询按钮
        driver.findElement(By.xpath("//*[@id=\"query_ticket\"]")).click();
        // 等待查询结果加载
        WebDriverWait wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10));
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"queryLeftTable\"] ")));

        // 等待日期选择区域加载完成
        WebElement dateElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"date_range\"]/ul/li[6]")));
        Thread.sleep(1000);

        // 执行鼠标悬停操作
        Actions actions = new Actions(driver);
        actions.moveToElement(dateElement).perform();
        dateElement.click();

        // 等待子元素加载完成再点击
        WebElement dateSpan = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"date_range\"]/ul/li[6]/span[2]")));
        dateSpan.click();


        driver.findElement(By.xpath("//*[@id=\"queryLeftForm\"]/div[3]/ul/li[2]")).click();
        driver.findElement(By.xpath("//*[@id='_ul_station_train_code']/li[last()]")).click();
        driver.findElement(By.xpath("//*[@id=\"sear-result\"]/span/label[1]")).click();
        takeScreenshot(screen);
    }
//test-code-end


    @AfterEach
    public void teardown() {
        this.driver.quit();
    }

    private void takeScreenshot(String fileName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmssSSS");
        String timestamp = dateFormat.format(new Date());
        String timestampedFileName = timestamp + "_" + fileName;
        File screenshotsDir = new File("screenshots");
        if (!screenshotsDir.exists()) {
            screenshotsDir.mkdirs();
        }
        String screenshotFilePath = screenshotsDir.getAbsolutePath() + File.separator + timestampedFileName;
        File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenshotFile, new File(screenshotFilePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}